<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">订单支付</block>
		</cu-custom>
		<view class="padding text-center margin-top" v-if="orderInfo != null">
			<view class="text-red text-bold text-xxl">¥<text class="margin-left-xs payment_price">{{orderInfo.paymentPrice}}</text></view>
			<view class="text-sm margin-top-xs" v-if="orderInfo.isPay == '0' && !orderInfo.status && canPay">请在<count-down :outTime="1000 * orderInfo.outTime"
				 @countDownDone="countDownDone"></count-down>内付款，超时订单将自动取消</view>
			<view class="text-sm margin-top-xs" v-if="!canPay">订单已超时取消</view>
			<view class="text-sm margin-top-sm">{{orderInfo.name}}</view>
		</view>
		<view class="cu-card">
			<radio-group @change="radioChange" class="cu-item cu-list menu-avatar block">
			    <view class="cu-item" v-for="(item, index) in paymentTypes" :key="item.value" :class="item.disabled != false ? 'grayscale' : ''">
				  <view class="cu-avatar lg bg-white" :style="'background-image:url('+item.icon+')'"></view>
			      <view class="content">
			        <view class="text-black">{{item.name}}</view>
			        <view class="text-gray text-sm flex">
			          <text class="text-cut text-xs" v-if="item.disabled != false">
						<text class="cuIcon-infofill margin-right-xs"></text> {{item.tip}}
					  </text>
			        </view>
			      </view>
			      <view class="action">
			        <radio class="red" :value="item.value" :checked="index === current" :disabled="item.disabled != false ? true : false"></radio>
			      </view>
			    </view>
			</radio-group>
		</view>
		<view class="cu-bar bg-white tabbar border " v-if="orderInfo">
			<button class="cu-btn block shadow-blur round pay-btn" :class="'bg-'+theme.themeColor" @tap="unifiedOrder" :loading="loading" :disabled="loading" type
			 v-if="orderInfo.isPay == '0' && !orderInfo.status && canPay">立即付款  ¥{{orderInfo.paymentPrice}}</button>
		</view>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	const util = require("utils/util.js");
	const app = getApp();
	import api from 'utils/api'
	import countDown from "components/count-down/index";
	import jweixin from '@/utils/jweixin'

	export default {
		components: {
			countDown
		},
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				orderInfo: null,
				orderId: null,
				canPay: false,
				paymentTypes: [
					{
						value: '1',
						name: '微信',
						icon: '',
						tip: 'PC、APP、微信小程序、公众号H5可使用',
						disabled: false,
					},
					{
						value: '2',
						name: '支付宝',
						icon: '',
						tip: 'PC、APP、普通H5可使用',
						// #ifdef APP-PLUS
						disabled: false,
						// #endif
						// #ifdef H5
						disabled: util.isWeiXinBrowser() ? true : false,
						// #endif
					}
				],
				current: null,
				loading: false
			}
		},
		onLoad(options) {
			// 保存别人分享来的 userCode
			util.saveSharerUserCode(options);
			let orderId = options.orderId
			this.orderId = orderId
			app.initPage().then(res => {
				this.orderGet(orderId);
			});
		},

		onShow() {
			app.initPage().then(res => {
				this.orderGet(this.orderId);
			});
		},

		methods: {
			orderGet(id) {
				let that = this;
				api.orderGet(id).then(res => {
					let orderInfo = res.data;
					this.orderInfo = orderInfo;
					if(orderInfo.outTime > 0){
						this.canPay = true
					}
					if(orderInfo.isPay === '1'){
						//支付成功跳转到支付结果页面
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/order/order-pay-result/index?orderId='+that.orderId
							});
						}, 1000);
					}
				});
			},
			countDownDone() {
				this.canPay = false
			},
			radioChange(evt) {
				for (let i = 0; i < this.paymentTypes.length; i++) {
					if (this.paymentTypes[i].value === evt.detail.value) {
						this.current = i;
						break;
					}
				}
			},
			unifiedOrder() {
				this.loading = true;
				var that = this;
				let orderInfo = this.orderInfo;
				if(this.current == null){
					this.loading = false;
					uni.showToast({
						title: '请选择支付工具',
						icon: 'none',
						duration: 2000
					});
				}else{
					let paymentType = this.paymentTypes[this.current].value
					api.unifiedOrder({
						paymentType: paymentType,
						id: orderInfo.id,
						// #ifdef MP-WEIXIN
						tradeType: 'JSAPI',
						// #endif
						// #ifdef H5
						tradeType: util.isWeiXinBrowser() ? 'JSAPI' : 'MWEB',
						returnUrl: window.location.protocol + '//' +window.location.host + '/pages/order/order-pay-result/index?orderId='+orderInfo.id+'&tenant_id='+orderInfo.tenantId,
						quitUrl: window.location.protocol + '//' +window.location.host + '/pages/order/order-detail/index?id='+orderInfo.id+'&tenant_id='+orderInfo.tenantId
						// #endif
						// #ifdef APP-PLUS
						tradeType: 'APP',
						// #endif
					}).then(res => {
						this.loading = false;
						if (orderInfo.paymentPrice <= 0) {
							//0元付款
							//支付成功跳转到支付结果页面
							uni.redirectTo({
								url: '/pages/order/order-pay-result/index?orderId=' + that.orderId
							});
						} else {
							let payData = res.data;
							// #ifdef MP-WEIXIN
							//微信小程序
							uni.requestPayment({
								provider: 'wxpay',
								timeStamp: payData.timeStamp,
								nonceStr: payData.nonceStr,
								package: payData.packageValue,
								signType: payData.signType,
								paySign: payData.paySign,
								success: function(res) {
									//支付成功跳转到支付结果页面
									// uni.redirectTo({
									// 	url: '/pages/order/order-pay-result/index?orderId=' + that.orderId
									// });
								},
								fail: function(res) {
									console.log('fail:' + JSON.stringify(res));
								},
								complete: function(res) {
									console.log(res);
								}
							});
							// #endif
							// #ifdef APP-PLUS
							//app微信支付
							if(paymentType === '1'){
								let orderInfo = {
									"appid": payData.appId,
									"noncestr": payData.nonceStr,
									"package": payData.packageValue,
									"partnerid": payData.partnerId,
									"prepayid": payData.prepayId,
									"timestamp": payData.timeStamp,
									"sign": payData.sign
								}
								uni.requestPayment({
									provider: 'wxpay',
									orderInfo: orderInfo,
									success: function(res) {
										//支付成功跳转到支付结果页面
										// uni.redirectTo({
										// 	url: '/pages/order/order-pay-result/index?orderId=' + that.orderId
										// });
									},
									fail: function(res) {
										console.log('fail:' + JSON.stringify(res));
									},
									complete: function(res) {
										console.log(res);
									}
								});
							}
							//app支付宝
							if(paymentType === '2'){
								let orderInfo = payData.body
								uni.requestPayment({
									provider: 'alipay',
									orderInfo: orderInfo,
									success: function(res) {
										//支付成功跳转到支付结果页面
										// uni.redirectTo({
										// 	url: '/pages/order/order-pay-result/index?orderId=' + that.orderId
										// });
									},
									fail: function(res) {
										console.log('fail:' + JSON.stringify(res));
									},
									complete: function(res) {
										console.log(res);
									}
								});
							}
							// #endif
							// #ifdef H5
							//微信公众号H5
							if(util.isWeiXinBrowser()){
								jweixin.payRequest(payData, res => {
									//支付成功跳转到支付结果页面
									// uni.redirectTo({
									// 	url: '/pages/order/order-pay-result/index?orderId=' + that.orderId
									// });
								}, e => {

								})
							}else{
								//支付宝H5
								if(paymentType === '2'){
									let form = payData.body
									//创建容器将返回的表单放进去然后新开一个页面
									let div = document.createElement('div')
									div.setAttribute("id", "alipay-div");
									div.innerHTML = form//此处form就是后台返回接收到的数据
									document.body.appendChild(div)
									// document.forms[0].setAttribute('target','_blank');//或者 myForm.target='_parent';
									document.forms[0].submit()
									document.getElementById("alipay-div").parentNode.removeChild(document.getElementById("alipay-div"));
								}
								//微信普通H5
								if(paymentType === '1'){
									let mwebUrl = payData.mwebUrl
									window.open(mwebUrl)
								}
							}
							// #endif
						}
					}).catch(() => {
						this.loading = false;
					});
				}
			},
		}
	}
</script>

<style>
	.pay-div{
		width: 100%;
		height: 140rpx;
		position: absolute;
		bottom: 0;
	}
	.pay-btn{
		margin: auto;
		width: 96%;
		height: 88rpx;
	}
	.payment_price{
		font-size: 80rpx;
	}
</style>
